package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.entity.Product;
import cn.tedu.coolshark.mapper.ProductMapper;
import org.apache.ibatis.annotations.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @Classname: ProductController
 * @Author: bromide
 * @CreateTime: 2022/5/18--11:47
 * @Version: V1.0
 * @Description:
 */
@RestController
public class ProductController {
    //@Value 注解这种写法是找到配置文件中的值读取出来并赋值给dirPath变量
    @Value("${dirPath}")
    private String dirPath;

    @Autowired(required = false)
    ProductMapper mapper;

    @RequestMapping("/product/insert")
    public void insert(@RequestBody Product product){
        product.setCreated(new Date());
        product.setViewCount((int)(101*Math.random()+100));
        mapper.insert(product);
    }

    @RequestMapping("/product/select")
    public List<Product> select(){
        return mapper.select();
    }

    @RequestMapping("/product/delete")
    public void delete(int id){
        //通过id查询商品的图片路径
        String url = mapper.selectUrlById(id);
        String filePath = dirPath+"/"+url;
        new File(filePath).delete();
        mapper.delete(id);
    }

    @RequestMapping("/product/select/index")
    public List<Product> selectByIndex(){
        return mapper.selectIndex();
    }

    @RequestMapping("/product/select/top")
    public List<Product> selectTop(){
        List<Product> list = mapper.selectTop();
        for(Product p : list){
            if (p.getTitle().length()>3){
                p.setTitle(p.getTitle().substring(0,3)+"...");
            }
        }
        return list;
    }

    @RequestMapping("/product/select/category")
    public List<Product> selectResult(int cid){
        return mapper.selectResult(cid);
    }

    @RequestMapping("/search")
    public List<Product> selectByWd(String wd){
        return mapper.selectByWd(wd);
    }
    @RequestMapping("/product/selectById")
    public Product selectById(int id){
        //让浏览量+1
        mapper.updateViewCount(id);
        return mapper.selectById(id);
    }
}
